package com.badlogic.agdwikisamples;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.badlogic.agdwikisamples.utils.CpuUsage;

public class TouchCpuUsageSample extends Activity implements OnTouchListener, OnClickListener
{
	static final String infoText = "Touch and drag your finger around the screen!\nNote that the usage is not exact but should show that there's something fishy going on.\nNote how sleeping does not help a lot!\n\ncpu usage: ";
	TextView tv;
	Button b;
	boolean doSleep = false;
	CpuUsage cpuUsage = new CpuUsage( );
	
	public void onCreate( Bundle bundle )
	{
		super.onCreate( bundle );
		
		tv = new TextView( this );
		tv.setText( infoText + cpuUsage.getUsage());
		tv.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f ) );
		tv.setOnTouchListener( this );
		
		b = new Button( this );
		b.setText( "Enable Sleeping" );
		b.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT ) );
		b.setOnClickListener( this );
		
		LinearLayout l = new LinearLayout( this );
		l.setOrientation( LinearLayout.VERTICAL );
		l.addView( b );
		l.addView( tv );
		
		setContentView( l );
		
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				tv.setText( infoText + (int)cpuUsage.getUsage() + "%");
				tv.postDelayed( this, 500 );
			}
			
		};
		
		tv.postDelayed( runnable, 500 );
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) 
	{
		if( doSleep )
			try{ Thread.sleep(20); } catch( Exception e ) { };
		return true;
	}
	
	@Override
	public void onClick(View v) 
	{
		doSleep = !doSleep;
		if( doSleep )
			b.setText( "Disable Sleeping" );
		else
			b.setText( "Enable Sleeping" );
	}
}
